import COS from 'cos-js-sdk-v5'

class ppCos {
	host = null
	token = null

	constructor(conf) {
		console.log("参数：", conf);
		this.host = conf.host
		this.token = conf.token
	}

	async hasTest(kwargs) {
		let picFile = await this.hasPicFile()
		console.log("选择图片", picFile);

		let cosToken = await this.hasCosToken(this.host, this.token)
		console.log("请求密钥", cosToken);

		let cosRequest = await this.hasCosRequest(cosToken, picFile, kwargs.path)
		console.log("上传对象", cosRequest);
		
		return cosRequest
	}

	hasCosRequest(token, file, path) {
		return new Promise((resolve, reject) => {
			let fileName = 'media/' + path + '/' + token.startTime + '_' + file.name;
			let cos = new COS({
				SecretId: token.credentials.tmpSecretId,
				SecretKey: token.credentials.tmpSecretKey,
				SecurityToken: token.credentials.sessionToken,
				StartTime: token.startTime,
				ExpiredTime: token.expiredTime
			});
			let response = cos.uploadFile({
				Bucket: token.account.bucket,
				Region: token.account.region,
				Key: fileName,
				Body: file,
				SliceSize: 1024 * 1024 * 5, // 大于1mb才进行分块上传				
			}, (err, data) => {
				if (err) {
					reject(err)
				} else {
					let logo = '/media' + data.Location.split('/media')[1]
					resolve(logo)
				}
			})
		})
	}
	hasPicFile() {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				success(res) {
					resolve(res.tempFiles[0])
				},
				fail(err) {
					reject(err)
				}
			})
		})
	}
	hasCosToken(host, token) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: host + '/api/cosSt/',
				method: 'POST',
				header: {
					'content-type': 'application/json',
					'authorization': token
				},
				success(res) {
					if (res.data.rescode === 200) {
						resolve(res.data.resmsg);
					} else {
						reject(res.data.rescode)
					}
				},
				fail(err) {
					reject(err)
				}
			})
		})
	}
}
export default ppCos